package com.homer.gps.track.helper;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;

import org.apache.commons.io.FileUtils;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.BaseColumns;
import android.provider.MediaStore;

public class ImageCaptHelper {

	private Activity mActivity;
	private Context mContext;

	private ArrayList<String> galleryList = new ArrayList<String>();

	private String sFilePath = "";
	private File currentFile = null;
	private Uri currentUri = null;

	public ImageCaptHelper(Context context, Activity activity, String directory, boolean moveToGallery) {
		this.mActivity = activity;
		this.mContext = context;
		fillPhotoList();
		setsFilePath(getTempFileString(directory));
	}

	public Uri getCurrentUri() {
		return currentUri;
	}

	@SuppressWarnings("deprecation")
	public String captureImage() {
		try {
			String path = null;
			String[] projection = { MediaStore.Images.ImageColumns.SIZE, MediaStore.Images.ImageColumns.DISPLAY_NAME, MediaStore.Images.ImageColumns.DATA, BaseColumns._ID, };
			Cursor c = null;
			Uri u = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
			if (currentFile != null) {
				if ((u != null) && (currentFile.length() > 0)) {
					c = mActivity.managedQuery(u, projection, null, null, null);
				}
				if ((c != null) && (c.moveToFirst())) {
					do {
						boolean bFound = false;
						for (String sGallery : galleryList) {
							if (sGallery.equalsIgnoreCase(c.getString(1))) {
								bFound = true;
								break;
							}
						}
						if (!bFound) {
							File f = new File(c.getString(2));
							if ((f.exists()) && (currentFile.length() < c.getLong(0)) && (currentFile.delete())) {
								try {
									currentFile.createNewFile();
									FileChannel source = null;
									FileChannel destination = null;
									try {
										source = new FileInputStream(f).getChannel();
										destination = new FileOutputStream(currentFile).getChannel();
										destination.transferFrom(source, 0, source.size());
										path = currentFile.getPath();
									} finally {
										if (source != null) {
											source.close();
										}
										if (destination != null) {
											destination.close();
										}
									}
								} catch (IOException e) {
									e.printStackTrace();
								}
							}
							ContentResolver cr = mContext.getContentResolver();
							cr.delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, BaseColumns._ID + "=" + c.getString(3), null);
							break;
						}
					} while (c.moveToNext());
				}
			}
			return path;
		} catch (Exception e) {
		}
		return null;
	}

	private void setsFilePath(String value) {
		sFilePath = value;
		currentFile = null;
		currentUri = null;
		if (!sFilePath.equalsIgnoreCase("")) {
			currentFile = new File(sFilePath);
			currentUri = Uri.fromFile(currentFile);
		}
	}

	@SuppressWarnings("deprecation")
	private void fillPhotoList() {
		galleryList.clear();
		String[] projection = { MediaStore.Images.ImageColumns.DISPLAY_NAME };
		Cursor c = null;
		Uri u = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
		if (u != null) {
			c = mActivity.managedQuery(u, projection, null, null, null);
		}
		if ((c != null) && (c.moveToFirst())) {
			do {

				galleryList.add(c.getString(0));
			} while (c.moveToNext());
		}
	}

	private String getTempFileString(String directory) {
		final File path = new File(directory);
		if (!path.exists()) {
			path.mkdir();
		}

		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_hhmmss", Locale.ENGLISH);
		String imageName = dateFormat.format(new Date(System.currentTimeMillis()));
		File image = new File(path, String.valueOf(imageName + ".jpg"));
		return image.getPath();
	}

	public String getImageFromGallery(Intent imageReturnedIntent) {
		String path = null;
		String[] projection = new String[] { MediaStore.Images.ImageColumns.DISPLAY_NAME, MediaStore.Images.ImageColumns.DATA };
		Cursor c = mContext.getContentResolver().query(imageReturnedIntent.getData(), projection, null, null, null);
		if (c != null && c.moveToFirst()) {
			String srcPath = c.getString(1);
			String destExt = sFilePath.substring(sFilePath.lastIndexOf('.'));
			String sourceExt = srcPath.substring(srcPath.lastIndexOf('.'));
			if (!destExt.equalsIgnoreCase(srcPath))
				sFilePath = sFilePath.replace(destExt, sourceExt);

			String destPath = sFilePath;
			try {
				FileUtils.copyFile(new File(srcPath), new File(destPath));
				path = destPath;
			} catch (IOException e) {
			}
		}
		c.close();
		return path;
	}

	public void setImageUri(Uri uri) {
		this.currentUri = uri;
	}

}
